package arrAndstr;

/*
    2. 两数相加
 */
public class T2 {
    static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public static void main(String[] args) {
        int[] arr1 = new int[]{9,9,9,9,9,9,9};
        int[] arr2 = new int[]{9,9,9,9};

        ListNode l1 = new ListNode();
        ListNode temp = l1;
        temp.val = arr1[0];
        for (int i = 1; i < arr1.length; i++) {
            temp.next = new ListNode();
            temp = temp.next;
            temp.val = arr1[i];
        }

        ListNode l2 = new ListNode();
        temp = l2;
        temp.val = arr2[0];
        for (int i = 1; i < arr2.length; i++) {
            temp.next = new ListNode();
            temp = temp.next;
            temp.val = arr2[i];
        }
        ListNode node = addTwoNumbers(l1, l2);
        while (node != null) {
            System.out.println(node.val);
            node = node.next;
        }

    }

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode node1 = l1;
        ListNode node2 = l2;

        while (true) {
            node1.val = node1.val + node2.val;

            if (node1.next == null) {
                node1.next = node2.next;
                break;
            }
            if (node2.next == null) break;

            node1 = node1.next;
            node2 = node2.next;
        }

        ListNode node = l1;
        while (node != null) {
            if (node.val >= 10) {
                if (node.next != null)  node.next.val += node.val/10;
                else node.next = new ListNode(node.val/10);
                node.val = node.val%10;
            }
            node = node.next;
        }

        return l1;
    }
}


